"""
@author: Leo
@version: 1.0.0
@file: mobile_views.py
@time: 2023/9/17 10:48 AM
"""
from datetime import timedelta

from django.contrib.auth.models import User
from django.core.cache import cache
from django.db import transaction
from django.utils.timezone import now

from lab.common.base_model_view_set import BaseModelViewSet
from lab.common.enums import ErrorCodeEnum
from lab.common.id_factory import id_factory
from lab.common.response import BadRequest, OK
from lab.settings import SMS_EXPIRE_TIME
from lab.user.models import ExtendedUser
from lab.user.auth.serializers import SmsSerializer, MobileLoginSerializer
from lab.utils.jwt_utils import JwtUtils
from lab.utils.sms_utils import SmsUtils


class SmsViewSet(BaseModelViewSet):
    """
    create:
        获取手机验证码
    """
    serializer_class = SmsSerializer

    def create(self, request, *args, **kwargs):
        phone_number = request.data.get('phone_number')
        if not phone_number:
            raise BadRequest('No phone number provided!')
        verification_code = SmsUtils.generate_verification_code()
        cache.set(phone_number, verification_code, timeout=SMS_EXPIRE_TIME * 60)
        SmsUtils.send_sms_single(phone_number, [verification_code, SMS_EXPIRE_TIME])
        return OK('Verification code sent successfully!')


class MobileLoginViewSet(BaseModelViewSet):
    """
    create:
        手机/验证码登录 - 第一次登录手机号码等信息会入库
    """
    serializer_class = MobileLoginSerializer

    def create(self, request, *args, **kwargs):
        phone_number = request.data.get('phone_number')
        verification_code = request.data.get('verification_code')
        if not phone_number or not verification_code:
            raise BadRequest('Invalid phone number or verification code!')

        if cache.get(phone_number) != verification_code:
            raise BadRequest(ErrorCodeEnum.INVALID_VERIFICATION_CODE.value)

        extended_user = ExtendedUser.objects.filter(phone_number=phone_number).first()
        if not extended_user:
            with transaction.atomic():
                user = User.objects.create(email=f'{phone_number}@anying.com',
                                           username=f'微信用户-{id_factory.get_unique_id()}')
                extended_user = ExtendedUser.objects.create(phone_number=phone_number, user_id=user.id, vip_expired_time=now()+timedelta(days=14))
        return OK({
            'user_id': extended_user.id,  # this is the extended user
            'user_name': extended_user.user.username,
            'token': JwtUtils.generate_jwt_token(extended_user.id, extended_user.user.username),
            'refresh_token': JwtUtils.generate_jwt_refresh_token(extended_user.id, extended_user.user.username)
        })
